import { login, getUser } from '@/api/user'
const state = {
  token: localStorage.getItem('home-token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    // console.log(8, token)
    state.token = token
    localStorage.setItem('home-token', token) // token的持久化
  },
  removeToken(state) {
    state.token = null // 清空vuex的token缓存
    localStorage.removeItem('home-token')// 删除token
  },
  setUserInfo(state, userInfo) {
    // console.log(13, userInfo)
    state.userInfo = { ...userInfo }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    store.commit('setToken', res.data.jwt)
    store.commit('setUserInfo', res.data.user)
  },
  // 获取用户信息
  async getUserInfo(store) {
    const { data } = await getUser()
    store.commit('setUserInfo', data)
  },
  // 退出
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

